//订单基础配置
import { useState, useEffect } from "react";
import AutoGetWaybill from "./AutoGetWaybill";
import AutoMergeOrder from "./AutoMergeOrder";
import FreightInterception from "./FreightInterception";
import OrderInventory from "./OrderInventory";
import JdCloudWarehouse from "./JdCloudWarehouse";
import { getOrderRulesOp, updateOrderRulesOp } from "../../service";
import ResetStyle from "@/pages/OrderModule/common/components/ResetStyle";
import { Tabs, message } from "antd";
import { useLocation } from "react-router-dom";
import { getSearchParamsObj } from "@/utils/utils.jsx";
import LogisticsReturn from "./LogisticsReturn";

const { TabPane } = Tabs;
const TabOrderBaseConfig = () => {
	const [tab, setTab] = useState("0");
	const [baseConfigData, setBaseConfigData] = useState({}); //订单基础配置数据

	const location = useLocation();

	//处理页面跳转
	// useEffect(() => {
	// 	if (location.pathname == "/views/order/rule") {
	// 		if (location.state?.tab) {
	// 			setTab(location.state?.tab + "");
	// 			window.history.replaceState("", "");
	// 		}
	// 	}
	// }, [location.pathname]);

	useEffect(() => {
		if (location.pathname == "/views/order/rule") {
			const urlParams = getSearchParamsObj(location.search);
			const { tab1, tab2 } = urlParams;
			setTab(tab2);
			if(location.state?.tabKey) {
				setTab(location.state?.tabKey);
			}
		}
	}, [location.pathname]);

	useEffect(() => {
		if (tab != 2 && tab != 1 && tab != 5) {
			getBaseConfigData();
		}
	}, [tab]);

	//获取订单基础配置数据
	const getBaseConfigData = async () => {
		window.START_LOADING();
		const { success, data = {} } = await getOrderRulesOp();
		if (success) {
			setBaseConfigData(data);
		}
		window.END_LOADING();
	};

	//修改订单基础配置数据
	const upDateBaseConfigData = async val => {
		window.START_LOADING();
		const { success, msg = "" } = await updateOrderRulesOp({
			id: baseConfigData.id,
			...val
		});
		if (success) {
			message.success(msg);
			getBaseConfigData();
		}
		window.END_LOADING();
	};

	//组件的props
	const TabPaneProps = {
		data: baseConfigData,
		handUpDateBaseConfigData(val) {
			upDateBaseConfigData(val);
		}
	};

	//自动合单的props
	const AutoMergeOrderProps = {
		tab
	};

	return (
		<Tabs
			activeKey={tab}
			onChange={val => {
				setTab(val);
			}}
		>
			<TabPane tab="订单库存" key="0">
				<OrderInventory {...TabPaneProps} />
			</TabPane>
			<TabPane tab="京东云仓" key="1">
				<JdCloudWarehouse {...AutoMergeOrderProps} />
			</TabPane>
			<TabPane tab="自动合单" key="2">
				<AutoMergeOrder {...AutoMergeOrderProps} />
			</TabPane>
			<TabPane tab="快递运费拦截" key="3">
				<FreightInterception {...TabPaneProps} />
			</TabPane>
			<TabPane tab="运单号获取" key="4">
				<AutoGetWaybill {...TabPaneProps} />
			</TabPane>
			<TabPane tab="物流回传" key="5">
				<LogisticsReturn { ...AutoMergeOrderProps } />
			</TabPane>
		</Tabs>
	);
};

export default ResetStyle(TabOrderBaseConfig, { wrappers: ["rule_base_config-reset"] });
